import pandas as pd # 导入数据分析模块
import numpy as np # 导入科学计算模块
from pyecharts.charts import Bar, Map, Line, Pie, Grid, Timeline, WordCloud, Map3D,  MapGlobe  # 导入条形图,地图,折线图,玫瑰图 ,grid并行组图组件
from pyecharts import options as opts # 导入配置项模块
from pyecharts.globals import ThemeType # 导入主题模块


####################################################################################
data = pd.read_csv('china_all_provinces_history_data_2022_09_16.csv') # 读取数据,
data['date'] = pd.to_datetime(data['date']) # 将日期这一列数据,设置为datatime64[ns]格式
data.set_index('date',inplace=True) # 将日期设置为索引

date_list  = pd.DataFrame(pd.date_range('2022-07-01','2022-09-14',freq='1D'))
date_list = date_list[0].apply(lambda x:x.strftime('%Y-%m-%d'))
data_list_total = {}
data_list_today = {}
for i in date_list:
    data_list_total[i] = data.loc[i,['province_name','total_confirm']].sort_values(by='total_confirm').values.tolist()[::-1]
    data_list_today[i] = data.loc[i, ['province_name', 'today_confirm']].values.tolist()[::-1]

# data_list_today['2021-07-24'].append(['青海',0])#补充数据，未爬到的数据
# data_list_today['2021-07-24'].append(['新疆',1])
# data_list_today['2021-07-24'].append(['西藏',0])
# data_list_today['2021-08-08'].append(['青海',0])
# data_list_today['2022-03-21'].append(['青海',0])
# data_list_today['2022-05-05'].append(['海南',0])
#
# data_list_total['2021-07-24'].append(['青海',18])
# data_list_total['2021-07-24'].append(['新疆',0])
# data_list_total['2021-07-24'].append(['西藏',1])
# data_list_total['2021-08-08'].append(['青海',18])
# data_list_total['2022-03-21'].append(['青海',18])
# data_list_total['2022-05-05'].append(['海南',288])
###########################################################################################
data3 = pd.read_csv('world_all_country_history_data_2022_09_16.csv')

############################################################################################
data4 = data3[data3['country_name'] == '中国']
cn_data = data4.copy()
cn_data['date'] = pd.to_datetime(cn_data['date']) # 将日期这一列数据,设置为datatime64[ns]格式
cn_data.set_index('date',inplace=True) # 将日期设置为索引

date_list  = pd.DataFrame(pd.date_range('2022-07-01','2022-09-14',freq='1D'))
date_list = date_list[0].apply(lambda x:x.strftime('%Y-%m-%d'))
cn_data_list = [[date,cn_data.loc[date,'total_confirm']] for date in date_list]
cnh_data_list = [[date,cn_data.loc[date,'total_heal']] for date in date_list]
cnd_data_list = [[date,cn_data.loc[date,'total_dead']] for date in date_list]

#气泡数据准备
marker_data = []
marker_data_h = []
marker_data_d = []
for i,j  in enumerate(date_list):
    md_data =  [0] * len(cn_data_list)
    mdh_data = [0] * len(cnh_data_list)
    mdd_data = [0] * len(cnd_data_list)
    md_data[i] = int(dict(cn_data_list)[j])
    mdh_data[i] = int(dict(cnh_data_list)[j])
    mdd_data[i] = int(dict(cnd_data_list)[j])
    marker_data.append(md_data)
    marker_data_h.append(mdh_data)
    marker_data_d.append(mdd_data)


def draw_mix(data,map_name,data_bar_today,data_bar_total,data_pie,data_map_today,data_map_total,type,line1,market1,line2,market2,line3,market3,data_word):
    t1 = Timeline(init_opts=opts.InitOpts(theme=ThemeType.CHALK,width='1536px',height='700px'))
    for z, date in enumerate(data):
        piecesC = [
            {"min": 10000, 'color': '#7f1100'},
            {"min": 1000, "max": 9999, 'color': '#bd1316'},
            {"min": 500, "max": 999, 'color': '#e64b45'},
            {"min": 100, "max": 499, 'color': '#ff8c71'},
            {"min": 1, "max": 99, 'color': '#fdd2a0'},
            {"max": 1}
        ]
    # 条形图
        bar = (Bar(init_opts=opts.InitOpts(theme=ThemeType.DARK))
            .add_xaxis([i[0] for i in data_bar_today[date][2:]])
            .add_yaxis('新增确诊', [i[1] for i in data_bar_today[date]][2:])
            .add_yaxis('累计确诊', [i[1] for i in data_bar_total[date]][2:])
            .set_global_opts(title_opts=opts.TitleOpts(title=map_name + '累计确诊人数条形图',
                                                      pos_left='7%', pos_top='1.5%',
                                                      title_textstyle_opts=opts.TextStyleOpts(font_size=14),

                                                      ),
                            legend_opts=opts.LegendOpts(pos_top='4.6%', pos_left='6.5%', is_show=True,
                                                        textstyle_opts=opts.TextStyleOpts(color='white')),
                            datazoom_opts=opts.DataZoomOpts(is_show=True, range_start=0, range_end=20, pos_top='43%', ),
                            xaxis_opts=opts.AxisOpts(name='',
                                                     type_='category',  # 轴的类型
                                                     name_location='center',  # 坐标轴轴名称的位置
                                                     name_gap=10,  # 坐标轴轴名称距离轴线的距离
                                                     axislabel_opts=opts.LabelOpts(color='white', is_show=True),
                                                     # 坐标轴标签的颜色

                                                     axistick_opts=opts.AxisTickOpts(is_show=True,  # 是否显示坐标轴刻度线
                                                                                     is_inside=True,  # 刻度线是否朝内
                                                                                     # 坐标轴刻度线的样式
                                                                                     linestyle_opts=opts.LineStyleOpts(
                                                                                         color='cyan')),
                                                     axisline_opts=opts.AxisLineOpts(symbol=['none', 'arrow'],
                                                                                     # 坐标轴的箭头的方向
                                                                                     # 坐标轴轴线的颜色
                                                                                     linestyle_opts=opts.LineStyleOpts(
                                                                                         color='cyan'))
                                                     ),
                            yaxis_opts=opts.AxisOpts(name='人数',  # x轴的名称
                                                     type_='value',  # 轴的类型
                                                     name_location='center',  # 坐标轴轴名称的位置
                                                     name_gap=10,  # 坐标轴轴名称距离轴线的距离
                                                     axislabel_opts=opts.LabelOpts(color='cyan', is_show=False),
                                                     # 坐标轴标签的颜色
                                                     axistick_opts=opts.AxisTickOpts(is_show=True,  # 是否显示坐标轴刻度线
                                                                                     is_inside=True,  # 刻度线是否朝内
                                                                                     # 坐标轴刻度线的样式
                                                                                     linestyle_opts=opts.LineStyleOpts(
                                                                                         color='cyan')),
                                                     axisline_opts=opts.AxisLineOpts(symbol=['none', 'arrow'],
                                                                                     # 坐标轴的箭头的方向
                                                                                     # 坐标轴轴线的颜色
                                                                                     linestyle_opts=opts.LineStyleOpts(
                                                                                         color='cyan'))
                                                     ),
                            # ----- 视觉映射配置项目
                            visualmap_opts=opts.VisualMapOpts(is_piecewise=True,
                                                              is_show=False,
                                                              range_text=['Highe', 'Low'],
                                                              textstyle_opts=opts.TextStyleOpts(color='cyan'),

                                                              # 设置分段颜色
                                                              max_=100000,  # 最大值
                                                              pos_right='1%',
                                                              pos_top='center',
                                                              pieces=piecesC,
                                                              ),


                            )
           )


    # 玫瑰图
        pie = (Pie(init_opts=opts.InitOpts(theme=ThemeType.DARK))
            .add('', data_pie[date],
                radius=['40', '100'],
                rosetype='area',
                center=['85.8%', '71%'],
                label_opts=opts.LabelOpts(formatter="{b}:{c}人"),
                )
            .set_global_opts(title_opts=opts.TitleOpts(title=map_name + '累计确诊玫瑰图',
                                                      pos_right='10%',
                                                      title_textstyle_opts=opts.TextStyleOpts(font_size=14),
                                                      pos_top='49%'),
                            legend_opts=opts.LegendOpts(is_show=False))

           )

    # 地图
        map_ = (Map(init_opts=opts.InitOpts(theme=ThemeType.CHALK))
                 .add('today_confirm', data_map_today[date], type,
                      label_opts=opts.LabelOpts(color='#fcfcfc', font_weight='bold', font_size=12,
                                                font_family='SimHei'), is_map_symbol_show=False)
                 .add('total_confirm', data_map_total[date], type,
                      label_opts=opts.LabelOpts(color='#fcfcfc', font_weight='bold', font_size=12,
                                                font_family='SimHei'), is_map_symbol_show=False)

                 .set_global_opts(title_opts=opts.TitleOpts(map_name + '疫情地图', pos_left='center',
                                                            title_textstyle_opts=opts.TextStyleOpts(font_size=20, ),
                                                            subtitle_textstyle_opts=opts.TextStyleOpts(font_size=18,
                                                                                                       color='white'),
                                                            pos_top='1%'),
                                  legend_opts=opts.LegendOpts(pos_top='7%',
                                                              textstyle_opts=opts.TextStyleOpts(color='white'),
                                                              is_show=True,selected_mode=''),
                                  visualmap_opts=opts.VisualMapOpts(is_piecewise=True, pieces=piecesC, pos_left='5%',
                                                                    pos_top='center',
                                                                    textstyle_opts=opts.TextStyleOpts(color='white')),
                                  )
                 )

        #词云
        couldword = (
            WordCloud(init_opts=opts.InitOpts(theme=ThemeType.CHALK,))
                .add('', data_pair=data_word[date], word_size_range=[20, 60],
                     textstyle_opts=opts.TextStyleOpts(font_family='Microsoft YaHei', font_weight='bold', ),
                     pos_left='70%', pos_right='1%', pos_top='1%', pos_bottom='63%', height='335px', width='500px',
                     shape='square')
                .set_global_opts(title_opts=opts.TitleOpts(title="疫情热点",
                                                           title_textstyle_opts=opts.TextStyleOpts(font_size=15),pos_right='12%',
                                                           pos_top='2.5%'))
        )

        line = (Line(init_opts=opts.InitOpts(theme=ThemeType.CHALK))
                .add_xaxis([i[0] for i in line1])
                .add_yaxis('总计确诊', [int(i[1]) for i in line1],
                       symbol='circle',
                       symbol_size=5,
                       label_opts=opts.LabelOpts(is_show=False),
                       is_smooth=True,
                       )
                .add_yaxis('总计确诊', market1[z],  # 气泡系列数据,
                       label_opts=opts.LabelOpts(is_show=False),
                       symbol_size=0,
                       linestyle_opts=opts.LineStyleOpts(is_show=False, width=0),
                       markpoint_opts=opts.MarkPointOpts(symbol_size=[40, 40],
                                                         data=[opts.MarkLineItem(type_='max')])
                       )
                .add_yaxis('累计治愈', [int(i[1]) for i in line2],
                           symbol='circle',
                           symbol_size=5,
                           label_opts=opts.LabelOpts(is_show=False),
                           is_smooth=True,
                           )
                .add_yaxis('累计治愈', market2[z],  # 气泡系列数据,
                           label_opts=opts.LabelOpts(is_show=False),
                           symbol_size=0,
                           linestyle_opts=opts.LineStyleOpts(is_show=False, width=0),
                           markpoint_opts=opts.MarkPointOpts(symbol_size=[40, 40],
                                                             data=[opts.MarkLineItem(type_='max')])
                           )
                .add_yaxis('累计死亡', [int(i[1]) for i in line3],
                           symbol='circle',
                           symbol_size=5,
                           label_opts=opts.LabelOpts(is_show=False),
                           is_smooth=True,
                           )
                .add_yaxis('累计死亡', market3[z],  # 气泡系列数据,
                           label_opts=opts.LabelOpts(is_show=False),
                           symbol_size=0,
                           linestyle_opts=opts.LineStyleOpts(is_show=False, width=0),
                           markpoint_opts=opts.MarkPointOpts(symbol_size=[40, 40],
                                                             data=[opts.MarkLineItem(type_='max')])
                           )
            .set_global_opts(
                                        title_opts=opts.TitleOpts(title=map_name+'时序折线图',
                                                          pos_left='8%',
                                                          title_textstyle_opts=opts.TextStyleOpts(font_size=14),pos_top='49%'),

                                     xaxis_opts=opts.AxisOpts(name='日期',
                                                              name_gap=20,
                                                              name_textstyle_opts=opts.TextStyleOpts(color='cyan',
                                                                                                     font_size=10),
                                                              axislabel_opts=opts.LabelOpts(color='cyan'),
                                                              axisline_opts=opts.AxisLineOpts(is_show=True,
                                                                                              symbol=['none', 'arrow'],


                                                                                              linestyle_opts=opts.LineStyleOpts(
                                                                                                  color='cyan')),
                                                              ),
                                     yaxis_opts=opts.AxisOpts(name='人数',
                                                              min_=0,
                                                              name_location='center',
                                                                name_gap=10,
                                                              name_textstyle_opts=opts.TextStyleOpts(color='cyan',
                                                                                                     ),
                                                              axislabel_opts=opts.LabelOpts(color='cyan',is_show=False),
                                                              axisline_opts=opts.AxisLineOpts(is_show=True,
                                                                                              #  设置轴线的颜色
                                                                                              linestyle_opts=opts.LineStyleOpts(
                                                                                                  color='cyan'),symbol=['none', 'arrow']),



                                                              ),
                                     tooltip_opts=opts.TooltipOpts(trigger='axis', axis_pointer_type='cross'),
                                     axispointer_opts=opts.AxisPointerOpts(is_show=True,
                                                                           label=opts.LabelOpts(color='black',
                                                                                                font_size=12,
                                                                                                font_family='SimHei')),
                                     legend_opts=opts.LegendOpts(is_show=True,pos_bottom='44%',pos_left='4.5%'),


                                     )
                    .set_series_opts(linestyle_opts=opts.LineStyleOpts(color='pink',
                                                                       width=2,
                                                                       ))
                    )

    # pos_left='67%', pos_right='8%', pos_bottom='55%', pos_top='8%'
        grid = (Grid(init_opts=opts.InitOpts(theme=ThemeType.CHALK, width='1536px',height='672px'))
                .add(bar,
                 grid_opts=opts.GridOpts(pos_left='2.6%',pos_right='77.6%',pos_top='11.5%',pos_bottom='57%'),
                 is_control_axis_index=True,
                 )
                .add(line,
                 grid_opts=opts.GridOpts(pos_left ='2.6%', pos_right = '77.6%', pos_top ='57%', pos_bottom = '10.5%'),
                 )
                .add(pie,
                 grid_opts=opts.GridOpts()
                 )
                .add(map_,
                 grid_opts=opts.GridOpts(is_contain_label=True))
                .add(couldword,grid_opts=opts.GridOpts())
            )
        t1.add(grid, f'{date}')
        t1.add_schema(play_interval=350,
                  is_loop_play=False,
                  orient='horizontal',
                  pos_left='8%',
                  pos_bottom='0.8%',
                  pos_right='10%'


                  )
    t1.render(map_name+'.html')

############################################################################### 数据准备
################################################################################
data = date_list
map_name = '中国'
data_bar_today = data_list_today
data_bar_total = data_list_total
data_pie = data_list_total
data_map_today = data_list_today
data_map_total = data_list_total
type = 'china'
line1 = cn_data_list
market1 = marker_data
line2 = cnh_data_list
market2 = marker_data_h
line3 = cnd_data_list
market3 = marker_data_d
data_word = data_list_today
#
draw_mix(data,map_name,data_bar_today,data_bar_total,data_pie,data_map_today,data_map_total,type,line1,market1,line2,market2,line3,market3,data_word)

################################################################################################################################################
# data = date_list
# map_name = '城市'
# data_bar_today = data_list_today
# data_bar_total = data_list_total
# data_pie = data_list_total
# data_map_today = data_list_today
# data_map_total = data_list_total
# type = 'china-cities'
# line1 = cn_data_list
# market1 = marker_data
# line2 = cnh_data_list
# market2 = marker_data_h
# line3 = cnd_data_list
# market3 = marker_data_d
# data_word = data_list_today
# #
# draw_mix(data,map_name,data_bar_today,data_bar_total,data_pie,data_map_today,data_map_total,type,line1,market1,line2,market2,line3,market3,data_word)